//
//  UploadRequest.m
//  Dear
//
//  Created by n22 on 15/7/20.
//  Copyright (c) 2015年 陈俊俊. All rights reserved.
//

#import "UploadRequest.h"
#import "LoginViewController.h"
@interface UploadRequest ()<BMKLocationServiceDelegate,UIAlertViewDelegate,BMKGeoCodeSearchDelegate>
{
    BMKLocationService* _locService;
    BMKGeoCodeSearch* _geocodesearch;

}
@property (nonatomic,strong)BMKUserLocation *userLocation;
@end
static UploadRequest *_sharedUpload = nil;
@implementation UploadRequest
#pragma mark - Class Method

+ (instancetype)sharedInstance {
    @synchronized (self){
        if (_sharedUpload == nil) {
            _sharedUpload = [[self alloc] init];
        }
    }
    return _sharedUpload;
}
+ (void)resetUpload
{
    _sharedUpload = nil;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        self.timer =   [NSTimer scheduledTimerWithTimeInterval:10*60 target:self selector:@selector(startLoc) userInfo:nil repeats:YES];
         _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
         _geocodesearch = [[BMKGeoCodeSearch alloc]init];
        _geocodesearch.delegate = self;
        //第一次登录成功
    }
    return self;
}

- (void)dealloc{
    _locService.delegate = nil;
    _locService = nil;
    if (_geocodesearch) {
        _geocodesearch = nil;
    }
}

- (void)startLoc{
    [_locService startUserLocationService];
}
- (void)getLocation{
    self.isLocation = YES;
    [self startLoc];
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"当前位置%f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [self uploadLoc:userLocation];
    
}
- (void)didFailToLocateUserWithError:(NSError *)error{
    //定位失败
    if ([self.delegate respondsToSelector:@selector(getLocationAddress:)]) {
        [self.delegate getLocationAddress:@"地址定位失败"];
    }
}

- (void)uploadLoc:(BMKUserLocation *)userLocation
{
    //停止定位
    [_locService stopUserLocationService];
    self.userLocation = userLocation;
    //反编码获取地址
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"编码成功");
    }else{
        NSLog(@"编码失败");
    }
}

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSString *address = @"";
    if (error == 0) {
        address = result.address;
    }else{
        address = @"位置未明";
    }
    
    if (self.isLocation) {
        self.isLocation = NO;
        if ([self.delegate respondsToSelector:@selector(getLocationAddress:)]) {
            [self.delegate getLocationAddress:address];
        }
    }else{
        [self getDictInformation:address];
    }
}
#pragma mark - 根据地址封装所有数据
- (void)getDictInformation:(NSString *)address
{
    //封装信息
    NSDictionary *locationDict = [self getDictToUserLocation:self.userLocation address:address];
    NSString *url = [ServerUrl stringByAppendingFormat:@"/%@",DearHttpLocation];
    [[HttpRequest sharedInstance] uploadPOST:url parameters:locationDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            NSLog(@"%@",responseObject);
            NSDictionary *dict = (NSDictionary *)responseObject;
            if ([dict[@"Result"] integerValue] == 0)
            {
                //上传成功要清空本地的位置信息
                if ([CJJHelper getMessageFromKey:LocationInformation]) {
                    [CJJHelper saveInformation:nil key:LocationInformation];
                }
            }else if ([dict[@"Result"] integerValue] == 2){
                //注销定时器
                if ([self.timer isValid]) {
                    [self.timer invalidate];
                    self.timer = nil;
                }
                UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"用户已经在其他设备上登录，你已被迫下线" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alertView show];
            }else {
                //保存本次的上传信息 取出数组中的第一个保存
                [self saveLocation:locationDict];
            }
        }else{
            //保存本次的上传信息 取出数组中的第一个保存
            [self saveLocation:locationDict];
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [DearLoadingView showTips:error];
        //保存本次的上传信息 取出数组中的第一个保存
        [self saveLocation:locationDict];
    }];

}

#pragma mark - 保存上传失败的信息
- (void)saveLocation:(NSDictionary *)locationDict{
    NSArray *locationArr = [CJJHelper objectFromJson:locationDict[@"poiJsonArray"]];
    if (locationArr.count > 0) {
        NSDictionary *locationDict = locationArr[0];
        //保存
        [CJJHelper saveInformation:locationDict key:LocationInformation];
    }
}

#pragma mark - 封装信息
- (NSDictionary *)getDictToUserLocation:(BMKUserLocation *)userLocation address:(NSString *)address{
    
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
    NSMutableArray *poiJson = [[NSMutableArray alloc]init];
    
    NSLog(@"%@",userLocation.subtitle);
    NSString  *latitude = [CJJHelper convertFrom:userLocation.location.coordinate.latitude];
    NSString  *longitude = [CJJHelper convertFrom:userLocation.location.coordinate.longitude];
    NSString  *accuracy = [CJJHelper convertFrom:userLocation.location.horizontalAccuracy];
    NSString  *add= [CJJHelper checkString:address];
    NSString  *type = [NSString stringWithFormat:@"%d",0];
    NSString  *userId = [CJJHelper checkString:[DearUser sharedInstance].userId];
    NSString  *speed  = [CJJHelper convertFrom:userLocation.location.speed];
    NSString  *elevation = [CJJHelper convertFrom:userLocation.location.altitude];
    NSString  *direction = [CJJHelper convertFrom:userLocation.location.course];
    NSString  *postTime = [CJJHelper stringFromDate:userLocation.location.timestamp];
    //封装字典
    NSMutableDictionary *oneObj = [[NSMutableDictionary alloc]init];
    [oneObj setValue:latitude forKey:@"latitude"];
    [oneObj setValue:longitude forKey:@"longitude"];
    [oneObj setValue:accuracy forKey:@"accuracy"];
    [oneObj setValue:add forKey:@"address"];
    [oneObj setValue:type forKey:@"type"];
    [oneObj setValue:userId forKey:@"userId"];
    [oneObj setValue:speed forKey:@"speed"];
    [oneObj setValue:elevation forKey:@"elevation"];
    [oneObj setValue:direction forKey:@"direction"];
    [oneObj setValue:postTime forKey:@"postTime"];
    
    [poiJson addObject:oneObj];
    NSString *poiJson1 = [CJJHelper dictionaryToJson:poiJson];

    //从本地读取定位信息，如果有就存放数组中，
    NSDictionary *  twoObj =[CJJHelper getMessageFromKey:LocationInformation];
    if (twoObj) {
        [poiJson addObject:twoObj];
    }
    //其他信息
    NSString *imsi = [CJJHelper checkString:@""];
    NSString *version = [CJJHelper checkString:@"1.0"];;
    NSString *phoneModel = [CJJHelper checkString:@""];
    NSString *phoneVersion = [CJJHelper checkString:@""];
    NSString *phoneVersionrelease = [CJJHelper checkString:@""];
    NSString *phoneBrand = [CJJHelper checkString:@""];;
    NSString *phoneSmsCenter = [CJJHelper checkString:@""];
    NSString *channelName = [CJJHelper checkString:@""];
    NSString *phoneNetwork = [CJJHelper checkString:@""];
    [dict setValue:imsi forKey:@"imsi"];
    [dict setValue:UUIDStr forKey:@"imei"];
    [dict setValue:poiJson1  forKey:@"poiJsonArray"];
    [dict setValue:[DearUser sharedInstance].userId forKey:@"userId"];
    [dict setValue:version forKey:@"version"];
    [dict setValue:phoneModel forKey:@"phoneModel"];
    [dict setValue:phoneVersion forKey:@"phoneVersion"];
    [dict setValue:phoneVersionrelease forKey:@"phoneVersionrelease"];
    [dict setValue:phoneBrand forKey:@"phoneBrand"];
    [dict setValue:phoneSmsCenter forKey:@"phoneSmsCenter"];
    [dict setValue:channelName forKey:@"channelName"];
    [dict setValue:phoneNetwork forKey:@"phoneNetwork"];
    
    return dict;
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [DearUser resetDear];
    if ([self.timer isValid]) {
        [self.timer invalidate];
    }
    [UploadRequest resetUpload];
    LoginViewController *lvc = [[LoginViewController alloc]init];
    [DearAppDelegate window].rootViewController = lvc;
}

@end
